package com.example.config;

import com.example.annotation.AsyncMessageHandler;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(name = "spring.rabbitmq.enabled", havingValue = "true", matchIfMissing = false)
public class MessageQueueConfig {
    
    @Bean
    public Queue defaultQueue() {
        return new Queue("default.queue", true);  // true表示队列持久化
    }
    
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }
    
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                System.out.println("消息发送成功: " + correlationData);
            } else {
                System.out.println("消息发送失败: " + cause);
            }
        });
        return template;
    }
    
    @Bean
    public AsyncMessageHandler asyncMessageHandler() {
        return new AsyncMessageHandler() {
            @Override
            public String queue() {
                return "default.queue";
            }
            
            @Override
            public String exchange() {
                return "";
            }
            
            @Override
            public String routingKey() {
                return "";
            }
            
            @Override
            public int priority() {
                return 0;
            }
            
            @Override
            public long ttl() {
                return 0;
            }
            
            @Override
            public int retryTimes() {
                return 3;  // 默认重试3次
            }
            
            @Override
            public int retryInterval() {
                return 5000;  // 默认重试间隔5秒
            }
            
            @Override
            public boolean enableLog() {
                return true;  // 默认启用日志
            }
            
            @Override
            public Class<? extends java.lang.annotation.Annotation> annotationType() {
                return AsyncMessageHandler.class;
            }
        };
    }
} 